package mark_2.io;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
    // 从URL下载图片并保存到指定路径
    public static boolean saveImage(String url, String savePath) {
        try (InputStream in = new URL(url).openStream();
             OutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            return true;
        } catch (IOException e) {
            System.err.println("下载图片失败: " + e.getMessage());
            return false;
        }
    }

    // 确保目录存在（不存在则创建）
    public static void ensureDirectoryExists(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    // 记录下载日志（格式：时间 | URL | 保存路径）
    public static void appendLog(String url, String savePath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        String log = time + " | " + url + " | " + savePath;

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("download_log.txt", true))) {
            writer.write(log);
            writer.newLine();
        } catch (IOException e) {
            System.err.println("记录日志失败: " + e.getMessage());
        }
    }
}

